//
//  AppDelegate.swift
//  新浪微博
//
//  Created by huami on 2019/10/10.
//  Copyright © 2019 huami. All rights reserved.
//

import AFNetworking
import SVProgressHUD
import UIKit
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        Bundle(path: "/Applications/InjectionIII.app/Contents/Resources/iOSInjection.bundle")?.load()

        window = UIWindow()

        setupAdditons()

        loadAppInfo()
        
        return true
    }
}

extension AppDelegate {
    private func setupAdditons() {
        // 1. 设置SVProgressHUD的最小解除时间
        SVProgressHUD.setMinimumDismissTimeInterval(1)
        // 2. 设置网络加载指示器
        AFNetworkActivityIndicatorManager.shared().isEnabled = true

        // 取得用户的授权的显示通知【上方的提示条/声音/BadgeNumber】
        if #available(iOS 10.0, *) {
            UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .carPlay, .sound]) { success, _ in
                print("授权" + (success ? "成功" : "失败"))
            }
        } else {
            let notifySettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
            UIApplication.shared.registerUserNotificationSettings(notifySettings)
        }
    }
}

extension AppDelegate {
    private func loadAppInfo() {
        DispatchQueue.global().async {
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 3) {
                // 1.url
                let url = Bundle.main.url(forResource: "main.json", withExtension: nil)
                // 2.nadata
                let data = NSData(contentsOf: url!)
                // 3.写入磁盘
                let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
                let jsonPath = (docDir! as NSString).appendingPathComponent("main.json")

                data?.write(toFile: jsonPath, atomically: true)

                print("应用程序加载完毕\(jsonPath)")
            }
        }
    }
}
